package com.neighbor.neighborhooduser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neighbor.neighborhooduser.pojo.PostComments;
import com.neighbor.neighborhooduser.pojo.Posts;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.pojo.dto.CommentDto;
import com.neighbor.neighborhooduser.service.IPostCommentsService;
import com.neighbor.neighborhooduser.service.IPostsService;
import com.neighbor.neighborhooduser.service.IUsersService;
import com.neighbor.neighborhooduser.utils.ReOpe;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 帖子评论表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@RestController

public class PostCommentsController {

    @Autowired
    private IPostsService postsService;
    @Autowired
    private IPostCommentsService postCommentsService;
    @Autowired
    IUsersService usersService;
    @Autowired
    private ReOpe reOpe;
    /**
     * 获取评论
     *
     * @param postId
     * @param commentDto 封装 postId, content
     * @param request
     * @return
     */
    @PostMapping("posts/{postId}/comments")
    public ResponseMsg setComment(@PathVariable Integer postId, @RequestBody CommentDto commentDto, HttpServletRequest request) {
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {
            return responseMsg;
        }
        Users user = (Users) responseMsg.getData();
        PostComments postComments = new PostComments();
        postComments.setPostId(postId);
        postComments.setUserId(user.getUserId());
        postComments.setContent(commentDto.getContent());
        postComments.setFatherCommentId(commentDto.getFatherCommentId());
        UpdateWrapper<Posts> wrapper = new UpdateWrapper<>();
        ResponseMsg msg = postsService.getPostById(postId, request);
        Posts post = (Posts) msg.getData();
        wrapper.set("reply_count",post.getReplyCount()+1)
                .eq("post_id",postId);
        postsService.update(wrapper);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "评论成功", postCommentsService.save(postComments));
    }



    @GetMapping("comments/{postId}")
    public ResponseMsg getCommentsByPostId(@PathVariable Integer postId) {
        try {
            // 查询父评论（father_comment_id为0的评论）
            QueryWrapper<PostComments> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("post_id", postId)
                    .eq("father_comment_id", 0)  // 使用0表示父评论
                    .orderByDesc("created_at");

            List<PostComments> mainComments = postCommentsService.list(queryWrapper);

            // 创建Map结构存储评论和回复
            Map<String, Object> resultMap = new HashMap<>();

            // 存储主评论列表
            List<Map<String, Object>> mainCommentsList = new ArrayList<>();

            // 存储回复的Map，key为主评论ID，value为该评论的回复列表
            Map<Integer, List<Map<String, Object>>> repliesMap = new HashMap<>();

            for (PostComments comment : mainComments) {
                // 将主评论转换为Map并添加到主评论列表
                Map<String, Object> commentMap = convertCommentToMap(comment);
                mainCommentsList.add(commentMap);

                // 查询该评论的回复（father_comment_id等于当前评论ID）
                QueryWrapper<PostComments> replyWrapper = new QueryWrapper<>();
                replyWrapper.eq("father_comment_id", comment.getCommentId())  // 使用评论ID作为父评论ID
                        .orderByAsc("created_at");

                List<PostComments> replies = postCommentsService.list(replyWrapper);

                // 将回复列表转换为Map列表
                List<Map<String, Object>> replyList = new ArrayList<>();
                for (PostComments reply : replies) {
                    replyList.add(convertCommentToMap(reply));
                }

                // 将回复列表放入repliesMap，以评论ID为键
                repliesMap.put(comment.getCommentId(), replyList);
            }

            // 将数据放入结果Map
            resultMap.put("mainComments", mainCommentsList);
            resultMap.put("replies", repliesMap);

            return ResponseMsg.getInstance(200,"获取评论成功", resultMap);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMsg.getInstance(400,"获取评论失败: " + e.getMessage());
        }
    }
    // 将评论对象转换为Map的方法
    private Map<String, Object> convertCommentToMap(PostComments comment) {
        Map<String, Object> commentMap = new HashMap<>();
        commentMap.put("commentId", comment.getCommentId());
        commentMap.put("postId", comment.getPostId());
        commentMap.put("content", comment.getContent());
        commentMap.put("createdAt", comment.getCreatedAt());
        commentMap.put("fatherCommentId", comment.getFatherCommentId());

        // 获取用户信息
        Users user = usersService.getById(comment.getUserId());
        if (user != null) {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("userId", user.getUserId());
            userMap.put("nickname", user.getNickname());
            userMap.put("avatar", user.getAvatar());
            commentMap.put("user", userMap);
        }

        return commentMap;
    }

    @PostMapping("/comments/{commentId}/replies")
    public ResponseMsg setReply(@PathVariable Integer commentId,
                                @RequestBody CommentDto commentDto,
                                HttpServletRequest request) {
        // 验证token
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {
            return responseMsg;
        }

        // 获取当前用户
        Users user = (Users) responseMsg.getData();

        try {
            // 创建评论回复
            PostComments postComments = new PostComments();
            postComments.setPostId(commentDto.getPostId());
            postComments.setUserId(user.getUserId());
            postComments.setContent(commentDto.getContent());
            postComments.setFatherCommentId(commentId);

            // 保存评论回复
            boolean saveResult = postCommentsService.save(postComments);
            if (!saveResult) {
                return ResponseMsg.getInstance(400,"回复失败");
            }

            // 更新帖子回复计数
            Posts post = postsService.getById(commentDto.getPostId());
            if (post != null) {
                post.setReplyCount(post.getReplyCount() + 1);
                postsService.updateById(post);
            }

            // 返回成功响应
            return ResponseMsg.getInstance(200,"回复成功", postComments);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMsg.getInstance(400,"服务器错误: " + e.getMessage());
        }
    }
}
